﻿#include "customlineitem.h"
#include "custompixmapitem.h"
#include "customellipseitem.h"
#include "common.h"

#include <QStyleOptionGraphicsItem>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsScene>
#include <QPainter>
#include <QDebug>

#define LINEWIDTH 1
#define LINENORMALCOLOR 0,0,0
#define LINESELECTEDCOLOR 0,0,255

CustomLineItem::CustomLineItem()
    : m_pEllipseItem(nullptr)
    , m_pTimer(nullptr)
    , m_pAnimation(nullptr)
{
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    setLineStyle();
}

CustomLineItem::CustomLineItem(CustomPixmapItem *pStartItem, CustomPixmapItem *pEndItem)
    : m_pStartItem(pStartItem)
    , m_pEndItem(pEndItem)
    , m_pEllipseItem(nullptr)
    , m_pTimer(nullptr)
    , m_pAnimation(nullptr)
{
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    setLineStyle();
}

void CustomLineItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QGraphicsLineItem::paint(painter, option, widget);
}

void CustomLineItem::mousePressEvent(QGraphicsSceneMouseEvent *pEvent)
{
    if (pEvent->button() & Qt::LeftButton) {
        this->setSelected(true);
    }
}

void CustomLineItem::setLineStartPixmapItem(CustomPixmapItem *pStartItem)
{
    m_pStartItem = pStartItem;
}

void CustomLineItem::setLineEndPixmapItem(CustomPixmapItem *pEndItem)
{
    m_pEndItem = pEndItem;
}

QPointF CustomLineItem::getStartPos()
{
    return m_pStartItem->pos();
}

QPointF CustomLineItem::getEndPos()
{
    return m_pEndItem->pos();
}

void CustomLineItem::updateLineItem()
{
    //更新线，根据结点的位置重绘
    QLineF line(mapFromItem(m_pStartItem, 20, 20), mapFromItem(m_pEndItem, 20, 20));
    setLine(line);
}

void CustomLineItem::setLineStyle()
{
    QPen pen;
    pen.setColor(QColor(LINENORMALCOLOR));
    pen.setWidth(LINEWIDTH);
    this->setPen(pen);
}

void CustomLineItem::drawLine()
{

}

void CustomLineItem::drawAnimation()
{
    CustomPixmapItem *pStartItem = m_pStartItem->isStart() ? m_pStartItem : m_pEndItem;
    CustomPixmapItem *pEndItem = m_pEndItem->isEnd() ? m_pEndItem : m_pStartItem;
    //画起点到终点
    if (m_pEllipseItem == nullptr && m_pStartItem != nullptr) {
        m_pEllipseItem = new QGraphicsEllipseItem();
        m_pEllipseItem->setBrush(QBrush(QColor(Qt::black)));
        m_pEllipseItem->setRect(0, 0, 20, 20);
        this->scene()->addItem(m_pEllipseItem);
    }
    m_pEllipseItem->show();

    if (m_pTimer == nullptr) m_pTimer = new QTimeLine(5000);
    m_pTimer->setFrameRange(0, 100);
    connect(m_pTimer, SIGNAL(finished()), this, SLOT(slotAnimationFinished()));

    if (m_pAnimation == nullptr) m_pAnimation = new QGraphicsItemAnimation;
    m_pAnimation->setItem(m_pEllipseItem);
    m_pAnimation->setTimeLine(m_pTimer);

    for (int i = 0; i <= 200; ++i) {
        m_pAnimation->setPosAt(i / 200.0, line().pointAt(i * 0.005) - QPoint(20, 20));
    }
    m_pTimer->start();
}

void CustomLineItem::slotAnimationFinished()
{
    m_pEllipseItem->hide();
}
